package com.taobao.itest.casegen.util;

import com.taobao.itest.casegen.RuleReceiver;
import com.taobao.itest.casegen.domain.Rule;
import com.taobao.itest.casegen.domain.RuleHouse;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: cangfeng.mxf
 * Date: 12-9-14
 * Time: 下午3:13
 * To change this template use File | Settings | File Templates.
 */
public class AgentRunnable implements Runnable {
    private Socket socket;
    /** rule house mapper */
    private RuleHouse ruleStore;

    public AgentRunnable(Socket sock){
        socket = sock;
        ruleStore = new RuleHouse();
        ruleStore.init();
    }
    @Override
    public void run() {
        //To change body of implemented methods use File | Settings | File Templates.
        try{
            Scanner scan = new Scanner(socket.getInputStream());
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
            String line = null;
            while(true){
                if(scan.hasNextLine()){
                    Rule r = new Rule();
                    r.setClientPort(socket.getPort());
                    r.setPattern(line);
                    r.setTackled(false);
                    boolean result = ruleStore.addRuleToHouse(r);
                    //回写, 通知client, 代码注入成功或者失败
                    writer.write(result ? "success.\n" : "fail.\n");
                }else{
                    sleep(1000);
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private void sleep(long millisecond){

    }
}
